package com.vote.www.service;

import com.vote.www.core.PropertiesData;
import com.vote.www.core.page.Pagination;
import com.vote.www.domain.Czjuserapprove;
import com.vote.www.domain.Czjuserinfo;
import com.vote.www.domain.Czjusermess;
import com.vote.www.domain.vo.TUser;
import com.vote.www.persistence.ApproveMapper;
import com.vote.www.persistence.CzjuserinfoMapper;
import com.vote.www.persistence.CzjusermessMapper;
import com.vote.www.utils.SendMessageUtil;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import tangwj.person.dao.ResourceDao;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 汤伟杰 on 2017/4/28.
 */
@Service
public class ApproveService {

    @Autowired
    private ApproveMapper approveMapper;
    @Autowired
    private ResourceDao resourceDao;
    @Autowired
    private CzjuserinfoMapper czjuserinfoMapper;
    @Autowired
    private CzjusermessMapper czjusermessMapper;
	@Resource
	private CzjuserapproveService czjuserapproveService;
	@Resource
	private JdbcTemplate jdbcTemplate;


    public Pagination getList(Map<String,Object> param, String pageNo, String pageSize) {
        Pagination p = new Pagination();
        p.setPageNo(Integer.parseInt(pageNo));
        p.setPageSize(Integer.parseInt(pageSize));
        param.putAll(p.toMap());
        int count=approveMapper.getTotalRows(param);
        List<Map<String,Object>> list=	approveMapper.getList(param);

        p.setList(list);
        p.setTotalCount(count);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).get("approveStatus")==null){
                try {
                    czjuserapproveService.aotoUpdate(Integer.parseInt(String.valueOf(list.get(i).get("userinfoId"))));
                    list.get(i).put("approveStatus",0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return p;
    }

    /**
     * 登录检查
     * @param username
     * @param password
     * @param req
     * @return
     */
    public boolean checkLogin(String username, String password, HttpServletRequest req) {
        String db_username = PropertiesData.getProperties("username");
        String db_password = PropertiesData.getProperties("password");
        if(db_username.equals(username)&&db_password.equals(password)){
            TUser user = new TUser();
            user.setUserId("1");
            user.setUsername(username);
            user.setPassword(password);
            req.getSession().setAttribute("user",user);
            return true;
        }
        return false;
    }

    public void getDetailById(String id, ModelMap model) throws Exception {
       /* Map<String, Object> param = new HashMap<String, Object>();
        param.put("userinfoId", id);
        List<Czjusermess> czjusermessList = czjusermessMapper.findCzjusermess(param);
        Czjusermess czjusermess = czjusermessList.get(0);
        czjusermess.setExt4(czjuserinfoService.voteNum(param));
        Map<String, Object> param2 = new HashMap<String, Object>();
        param2.put("id", id);
        Czjuserinfo czjuserinfo = czjuserinfoMapper.getCzjuserinfo(param2);

        Map<String, Object> map = jdbcTemplate.queryForMap("select voteNum from czj_votenum where userInfoId='" + id + "' limit 1");
        Object votenum = map.get("voteNum");
        if(votenum!=null){
            model.addAttribute("voteNum", votenum);
        }

        model.addAttribute("userinfo", czjuserinfo);
        model.addAttribute("usermess", czjusermess);*/

        Czjuserapprove czjuserapprove = (Czjuserapprove) jdbcTemplate.queryForObject("select * from czj_userapprove where userapproveId='" + id + "'", new BeanPropertyRowMapper(Czjuserapprove.class));
        try {
            czjuserapprove.setAge(czjuserapproveService.idcardToAge(czjuserapprove.getIdCard()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("entity",czjuserapprove);

 }

    /**
     *
     * @param i 审批状态  0审核中，1审核通过 2 审核不通过
     *@param id userinfo 主键
     * @param req
     * @param resp    @throws Exception
     * @param vodeoUri 
     */
    public void setApproveStatus(int i, String id,HttpServletRequest req, HttpServletResponse resp) throws Exception {
        czjuserapproveService.updateApproveStatus(i,id);
        Czjuserapprove czjuserapprove = (Czjuserapprove) jdbcTemplate.queryForObject("select * from czj_userapprove where userapproveId='"+id+"'",new BeanPropertyRowMapper(Czjuserapprove.class));
        if(i==1){
            Map<String,Object> msg = czjuserapproveService.isuse(1,czjuserapprove.getUserapproveId());
        }

        sendSms(i, czjuserapprove.getTelephone(), req, resp);
    }

    private void sendSms(int i, String phone, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //发送短信
        if(StringUtils.isNotBlank(phone)){
            HashMap<String, Object> result = SendMessageUtil.send(phone, resp, req, ""+(i+1));
            if (!"000000".equals(result.get("statusCode"))) {
                if(i==1){
                    throw new Exception("向用户发送审批通过消息失败！详细："+result.get("statusMsg"));
                }else if(i==2){
                    throw new Exception("向用户发送审批不通过消息失败！详细："+result.get("statusMsg"));
                }

            }
        }
    }

	public void updateUrl(String userapproveId, String vodeoUri) {
		czjuserapproveService.updateUrl(userapproveId,vodeoUri);
	}


}
